package cn.easybuy.web.backend;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSON;

import cn.easybuy.entity.Product;
import cn.easybuy.entity.Product_category;
import cn.easybuy.service.product.ProductService;
import cn.easybuy.service.product.ProductServiceImpl;
import cn.easybuy.service.product.Product_CategoryService;
import cn.easybuy.service.product.Product_CategoryServiceImpl;
import cn.easybuy.utils.ProductPage;

public class ProductListServlet extends HttpServlet {

	public ProductListServlet() {
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String action = request.getParameter("action");
		PrintWriter out = response.getWriter();
		ProductService ps = new ProductServiceImpl();
		Product_CategoryService pcs=new Product_CategoryServiceImpl();	
		if(action.equals("pageShow")){
			ProductPage page = new ProductPage();
			//获取页码
			String pageNo = request.getParameter("pageNo");
			if(pageNo==null){
				pageNo="1";
			}
			//每页数据量
			int pageSize = 5;
			//获取数据总量
			int count = ps.getCount();
			System.out.println(count);
			page.setPageNo(Integer.parseInt(pageNo));
			page.setPageSize(pageSize);
			page.setDataNum(count);
			page.setList(ps.getPageList(Integer.parseInt(pageNo), pageSize));
			request.setAttribute("page", page);
			request.getRequestDispatcher("Member_ProductList.jsp").forward(request, response);
		}else if(action.equals("del")){
			String id = request.getParameter("id");
			int i = ps.delProduct(id);
			if(i>0){
				out.print("<script>");
				out.print("alert('删除成功!');");
				out.print("window.location.href='ProductListServlet?action=pageShow';");
				out.print("</script>");
			}else{
				out.print("<script>");
				out.print("alert('删除失败!');");
				out.print("window.location.href='ProductListServlet?action=pageShow';");
				out.print("</script>");
			}
		}else if(action.equals("category")){ //使用Ajax请求 返回Json查询分类数据 提供给修改商品中的分类数据显示
			String category = request.getParameter("category");
			List<List<Product_category>>list = pcs.getList();

			if(category.equals("two")){
				String id = request.getParameter("id");
				List<Product_category>listTwo=new ArrayList<Product_category>();
				for (Product_category product_category : list.get(1)) {
					if(Integer.parseInt(id)==product_category.getParentId()){
						listTwo.add(product_category);
					}
				}
				String json = JSON.toJSONString(listTwo);
				out.print(json);
			}else if(category.equals("three")){
				String id = request.getParameter("id");
				List<Product_category>listThree=new ArrayList<Product_category>();
				for (Product_category product_category : list.get(2)) {
					if(Integer.parseInt(id)==product_category.getParentId()){
						listThree.add(product_category);
					}
				}
				String json = JSON.toJSONString(listThree);
				out.print(json);
			}
		}else if(action.equals("update")){
			String id = request.getParameter("id");
			Product product = ps.findProductById(id);
			request.setAttribute("list1",pcs.getList().get(0));
			request.setAttribute("list2",pcs.getList().get(1));
			request.setAttribute("list3",pcs.getList().get(2));
			request.setAttribute("product", product);
			request.getRequestDispatcher("Member_AddAndUpdateProduct.jsp").forward(request, response);
		}else if(action.equals("addUpdate")){
			String fileName = "";//上传的文件名字
			//创建商品对象
			Product p = new Product();
			//文件上传
			//判断表单类型
			boolean flag =ServletFileUpload.isMultipartContent(request);
			//文件存储路径
			String filePath = request.getSession().getServletContext().getRealPath("statics/productImg/");
			//System.out.println(filePath);
			if(flag){
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload fileUpload = new ServletFileUpload(factory);
				//解析表单
				List<FileItem>items = null;
				try{
					items = fileUpload.parseRequest(request);
				}catch (FileUploadException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				//生成迭代器
				Iterator<FileItem>iter = items.iterator();
				int i = 0;
				while(iter.hasNext()){
					i++;
					FileItem item = iter.next();
					//普通表单对象
					if(item.isFormField()){
						String name=item.getString("utf-8");
						fileName=item.getFieldName();
						if(fileName.equals("name")){
							p.setName(item.getString("utf-8"));
						}
						if(fileName.equals("price")){
							p.setPrice(Float.parseFloat(item.getString("utf-8")));
						}
						if(fileName.equals("stock")){
							p.setStock(Integer.parseInt(item.getString("utf-8")));
						}
						if(fileName.equals("categoryLevel1Id")){
							p.setCategoryLevel1Id(Integer.parseInt(item.getString("utf-8")));
						}
						if(fileName.equals("categoryLevel2Id")){
							p.setCategoryLevel2Id(Integer.parseInt(item.getString("utf-8")));
						}
						if(fileName.equals("categoryLevel3Id")){
							p.setCategoryLevel3Id(Integer.parseInt(item.getString("utf-8")));
						}
						if(fileName.equals("description")){
							p.setDescription(item.getString("utf-8"));
						}
						if(fileName.equals("id")){
							p.setId(Integer.parseInt(item.getString("utf-8")));
						}
						if(fileName.equals("photoimg")){
							p.setFileName(item.getString("utf-8"));
						}
					}else{
						fileName=item.getName();
						//设置可选类型
						List<String> ext=Arrays.asList("png","jpg","JPG","PNG","gif","GIF");
						//获取文件的后缀
						String suffix=fileName.substring(fileName.lastIndexOf(".")+1);
						//判断文件类型
						if(!ext.contains(suffix)){
							//不包含文件类型 且后缀不等于空 则禁止修改
							if(suffix!=""){
								out.print("<script type=text/javascript>");
								out.print("alert('选择文件类型错误，不允许修改');");
								out.print("window.history.back();");
								out.print("</script>");
								return;
							}
						}else{
							//判断文件是否为空，不为空则执行上传操作
							if(fileName!=null &&!fileName.equals("")){
								//创建新文件
								File newFile=new File(filePath,fileName);
								try {
									item.write(newFile);
									//文件名
									p.setFileName(item.getName());
									session.setAttribute("filename", p.getFileName());
									out.print("<script type=text/javascript>");
									out.print("alert('文件上传成功');");
									out.print("</script>");
								} catch (Exception e) {
									e.printStackTrace();
								}
							}else{
								out.print("<script type=text/javascript>");
					    		out.print("alert('文件为空，上传错误');");
					    		out.print("window.history.back();");
					    		out.print("</script>");
					    		return;
							}
						}
					}
				}
				System.out.println("当前图片为："+p.getFileName());
				//-1代表新增 非-1代表修改
				if(p.getId()==-1){
					int index = ps.addProduct(p);
					if(index>0){
						out.print("<script type=text/javascript>");
			    		out.print("alert('商品添加成功');");
			    		out.print("window.location.href='ProductListServlet?action=pageShow';");
			    		out.print("</script>");
					}else{
						out.print("<script type=text/javascript>");
			    		out.print("alert('商品添加失败');");
			    		out.print("window.location.href='ProductListServlet?action=pageShow';");
			    		out.print("</script>");
					}
				}else{
					int index = ps.updateProduct(p);
					System.out.println(index);
					if(index>0){
						out.print("<script type=text/javascript>");
			    		out.print("alert('商品修改成功');");
			    		out.print("window.location.href='ProductListServlet?action=pageShow';");
			    		out.print("</script>");
					}else{
						out.print("<script type=text/javascript>");
			    		out.print("alert('商品修改失败');");
			    		out.print("window.location.href='ProductListServlet?action=pageShow';");
			    		out.print("</script>");
					}
				}
			}
		}
	}
}